package com.guli.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.edu.entity.Chapter;
import com.guli.edu.entity.Video;
import com.guli.edu.entity.vo.ChapterVo;
import com.guli.edu.entity.vo.VideoVo;
import com.guli.edu.mapper.ChapterMapper;
import com.guli.edu.mapper.VideoMapper;
import com.guli.edu.service.ChapterService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author ZhaoZhenyu
 * @since 2022-09-26
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoMapper videoMapper;

    // 得到 课程 对应 全部章节集合 里面含有对应的视频结合
    @Override
    public List<ChapterVo> nestedListChapterByCourseId(String courseId) {

        //  得到全部章节集合
        List<Chapter> chapterList = baseMapper.selectList(new QueryWrapper<Chapter>().eq("course_id", courseId).orderByAsc("sort"));
        // 得到全部视频集合
        List<Video> videoList = videoMapper.selectList(new QueryWrapper<Video>().eq("course_id", courseId).orderByAsc("sort"));

        // 遍历章节结合填充到Vo
        ArrayList<ChapterVo> chapterVoList = new ArrayList<>();
        for (Chapter chapter : chapterList) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            // 所有video的vo放入集合
            ArrayList<VideoVo> videoVoList = new ArrayList<>();
            for (Video video : videoList) {
                // chapter的id对应的视频加进去
                if (chapter.getId().equals(video.getChapterId())) {
                    VideoVo videoVo = new VideoVo();
                    // 判断video里面的ifFree来赋值videoVo的free  0收费 1免费
                    videoVo.setFree(video.getIsFree() == 1);
                    BeanUtils.copyProperties(video,videoVo);
                    videoVoList.add(videoVo);
                }
            }
            // videoVo的集合放入对应的chapterVo
            chapterVo.setChildren(videoVoList);
            // chapterVo放入集合中
            chapterVoList.add(chapterVo);
        }
        return chapterVoList;
    }

}
